package com;


import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.widgets.*;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.SimpleFormatter;
import java.util.stream.Collectors;


public class Test {
    private static final Logger logger = LoggerFactory.getLogger(ReadPDFUtil.class);
    private static Shell shell = null;
    private static final String type = ".pdf";
    private static final Integer LEN = 1;

    private static final String[] colors = {"input", "text"};


    public static void main(String[] args) {
        Display display = new Display();
        shell = new Shell(display);
        shell.setText("SWT Browser Test");
        shell.setSize(800, 1400);

        final Text text = new Text(shell, SWT.BORDER);
        text.setBounds(110, 5, 560, 40);
        Button button = new Button(shell, SWT.BORDER);
        button.setBounds(680, 5, 100, 40);
        button.setText("选择");

        Label label = new Label(shell, SWT.LEFT);
        label.setText("请选择 :");
        label.setBounds(5, 5, 100, 40);

        Browser browser = createBrowser(shell);

        button.addListener(SWT.Selection, new Listener() {
            public void handleEvent(Event event) {
                btnClick(browser);
                //btnClickThread(display,browser);
            }
        });

        shell.open();
        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) {
                display.sleep();
            }
        }
        display.dispose();

    }

    private static Browser createBrowser(Shell shell) {
        Browser browser = new Browser(shell, SWT.FILL);
        sizeFunc(shell, browser);
        return browser;
    }

    private static void sizeFunc(Shell shell, final Browser browser) {
        shell.addPaintListener(new PaintListener() {

            @Override
            public void paintControl(org.eclipse.swt.events.PaintEvent e) {
                browser.setBounds(5, 45, e.width - 20, e.height - 20);
            }
        });
    }


    private static void btnClickThread(Display display, final Browser browser) {
        if (display.isDisposed()) {
            Runnable runnable = new Runnable() {
                public void run() {
                    btnClick(browser);
                }
            };
            display.syncExec(runnable);
        }

    }


    private static void btnClick(Browser browser) {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        fileChooser.setFileFilter(new FileFilter() {

            @Override
            public String getDescription() {
                // TODO Auto-generated method stub
                return "PDF文件(*" + type + ")";
            }

            @Override
            public boolean accept(File f) {
                if (StringUtils.indexOf(f.getName(), ".") == -1) {
                    return true;
                }
                return StringUtils.endsWithIgnoreCase(f.getName(), type);
            }
        });
        int result = fileChooser.showDialog(null, "选择文件");
        if (result == JFileChooser.APPROVE_OPTION) {
//            String htmlString = ReadPDFUtil.readPDF(fileChooser.getSelectedFile().getAbsolutePath());
//               browser.setText(htmlString, false);


//            readAloud(htmlString, browser);
        }

    }

    private static void btnClick(Browser browser, Display display) {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        fileChooser.setFileFilter(new FileFilter() {

            @Override
            public String getDescription() {
                // TODO Auto-generated method stub
                return "PDF文件(*" + type + ")";
            }

            @Override
            public boolean accept(File f) {
                if (StringUtils.indexOf(f.getName(), ".") == -1) {
                    return true;
                }
                return StringUtils.endsWithIgnoreCase(f.getName(), type);
            }
        });
        int result = fileChooser.showDialog(null, "选择文件");
        if (result == JFileChooser.APPROVE_OPTION) {
//            String htmlString = ReadPDFUtil.readPDF(fileChooser.getSelectedFile().getAbsolutePath());
            // browser.setText(htmlString, false);
//            readAloud(htmlString, browser);
        }

    }

    private static void readAloud(String html, Browser browser) {
        Document document = Jsoup.parse(html);
        if (Objects.isNull(document)) {
            return;
        }
        Elements es = document.getAllElements();
        if (CollectionUtils.isEmpty(es)) {
            return;
        }

        java.util.List<Element> esList = es.stream().filter(e -> e.hasText()).collect(Collectors.toList());

        AtomicInteger atomic = new AtomicInteger(1);
        int size = CollectionUtils.size(esList);
        if (size == 0) {
            return;
        }

        new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub

                Display.getDefault().asyncExec(new Runnable() {

                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        do {
//                            String html = readAloud(es, document, browser, atomic);
//                            if(StringUtils.isNotEmpty(html)){
//                                browser.setText(html);
//
//                            }
                            String html = "<div>测试:</div>"+atomic.get();
                            browser.setText(html);
                        //    sleepFun();
                            atomic.getAndAdd(1);
                        } while (atomic.get() <= size);
                    }
                });
            }
        }).start();
//        do {
//            readAloud(es, document, browser, atomic);
//        } while (atomic.get() <= size);
    }

    private static String  readAloud(java.util.List<Element> esList, Document document, Browser browser, AtomicInteger atomic) {

        Element element = esList.get(atomic.getAndAdd(1));

        if (Objects.isNull(element)) {
            return null;
        }

        Elements children = element.children();
        String txt = StringUtils.trim(element.text());
        int size = CollectionUtils.isEmpty(children) ? 0 : CollectionUtils.size(children);

        if (size == 0 && isIgnorColor(element.tagName())) {
            String style = element.attr("style");
            if (Objects.isNull(style)) {
                style = "";
            }
            style = style + ";color:red;fill:red;";
            element.attr("style", style);
            return document.html();
        }
        return null;
    }

    private static boolean isIgnorColor(String tagName) {
        for (String sourTagName : colors) {
            if (StringUtils.equalsIgnoreCase(sourTagName, tagName)) {
                return true;
            }
        }
        return false;
    }

    private static  void sleepFun(){
        try {
            Thread.sleep(1000);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

//	private static void readAloud(Document document,Browser browser) {
//		Elements elements = document.children();
//		if(CollectionUtils.isNotEmpty(elements)) {
//			elements.forEach(el->{
//				readChild(el,browser,document);
//			});
//		}
//	}

//	private static void readChild(Element el,Browser browser,Document document) {
//		if(Objects.nonNull(el)) {
//			Elements es = el.children();
//			if(CollectionUtils.isNotEmpty(es)) {
//				es.forEach(childEL->{
//					readChild(childEL,browser,document);
//				});
//			}else {
//				String text = el.text();
//				boolean flag = true;
//				for (String tagName : colors) {
//					if(StringUtils.equalsIgnoreCase(el.tagName(), tagName)) {
//						String style = el .attr("style");
//						if(Objects.isNull(style)) {
//							style = "";
//						}
//						style = style+";color:red";
//						el.attr("style", style);
//						
//						flag = false;
//						break;
//					}
//				}
//				
//				if(flag && StringUtils.isNotEmpty(StringUtils.trim(text))) {
//					el.append("<dd style='color:red'>"+text+"</dd>");
//				}
//				
//				browser.setText(document.html(), false);
//				try {
//					Thread.sleep(1000);
//				} catch (InterruptedException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
//			}
//		}
//	}


//	private static void readAloud(String html,Browser browser) {
//		new Thread(new Runnable() {
//
//			@Override
//			public void run() {
//				int length = StringUtils.length(html);
//				Document document = Jsoup.parse(html);
//				String text = document.text();
//				int index = 0;
//				for (int i = 0; i < length; i++) {
//					int len = length-i> LEN?LEN:length-i;
//					String cha = StringUtils.substring(text, i,i+len);
//					if(StringUtils.isNotEmpty(StringUtils.trim(cha))) {
//					
//						int index1 = StringUtils.indexOf(html, cha,index);
//						
//						String html1 = StringUtils.substring(html, index1,index1+1);
//						String html2 = StringUtils.substring(html, 0,index1);
//						String html3 = StringUtils.substring(html, index1+1);
//						
//						String html4 = html2+"<cccc color='red'>"+cha+"</cccc>"+html3;
//						Integer index12Integer = i;
//						Display.getDefault().asyncExec(new Runnable() {
//	
//							@Override
//							public void run() {
//								browser.setText(html4,false);
//								try {
//									FileUtils.write(new File("E:\\3\\7\\"+index12Integer+".html"), html4,"UTF-8");
//								} catch (IOException e) {
//									// TODO Auto-generated catch block
//									e.printStackTrace();
//								}
//							}});
//					
//						  try {
//							Thread.sleep(1000);
//						} catch (InterruptedException e) {
//							// TODO Auto-generated catch block
//							e.printStackTrace();
//						}
//					}
//					
//					logger.debug("[{}]",cha);
//				}
//			}
//			
//		}).start();

}
